﻿using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System;
using System.Threading;

public class SyncSocketClient : MonoBehaviour{
	private int port = 8309;
	private string hostIP = "192.168.1.133";
	private Socket client;

	void Start () {
		IPEndPoint remoteEp = new IPEndPoint(IPAddress.Parse(hostIP), port);
		client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        print("Connect to host...");
        client.Connect(remoteEp);
        if (!client.Connected)
            print("Unable to connect to host");
        else
            print("Success to connect to host");
	}

    void Update()
    {
        if (client != null && client.Connected)
        {
            if (client.Poll(10, SelectMode.SelectRead))
            {
                byte[] buffer = new byte[1024];
                print("This socket is readable");
                int length = client.Receive(buffer);
                byte[] receiveData = new byte[length];
                Array.Copy(buffer, 0, receiveData, 0, length);
                string str = Encoding.UTF8.GetString(receiveData);
                print("receive msg : " + str);
                GameObject go = GameObject.FindWithTag("MainCamera");
                ChatUIScript cUIs = go.transform.GetComponent<ChatUIScript>();
                cUIs.AreaMsg += str + "\n";
            }
            else if (client.Poll(10, SelectMode.SelectError))
            {
                print("This socket has an error");
                OnApplicationQuit();
            }
        }
    }
	
	public void Send(string data){
		byte[] bs = Encoding.UTF8.GetBytes(data);
		SendData (bs, 10006);
	}
		
	void SendData(byte[] data, ushort cmd){
		if(client.Connected){
			ushort len = (ushort)(data.Length + 5);
			byte[] sendData = new byte[len];
			sendData[0] = (byte)(len >> 8);
			sendData[1] = (byte)len;
			sendData[2] = 0;
			sendData[3] = (byte)(cmd >> 8);
			sendData[4] = (byte)cmd;
			Array.Copy(data, 0, sendData, 5, len - 5);
            client.Send(sendData);
		}
	}

    void OnApplicationQuit()
    {
        print("Exit");
        if (client != null && client.Connected)
        {
            client.Close();
        }
    }
}
